package com.example.hostapp

import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.HandlerThread
import android.os.Looper
import android.os.Message
import android.os.Messenger
import android.util.Log
import android.view.SurfaceControlViewHost
import android.view.SurfaceView
import androidx.annotation.RequiresApi
import java.lang.ref.WeakReference
import com.example.utils.MessengerUtil
import com.example.utils.MessengerUtil.Companion.KEY_CLIENT_SURFACEPKG

object HostManager {
    private lateinit var listener: textListener

    // 在类成员变量中初始化
    private val handlerThread = HandlerThread("SurfaceHandler").apply { start() }

    val TAG = this::class.simpleName
    var isSurfeced = false

    var serverMessenger: Messenger = Messenger(MyHandler(handlerThread.looper))     // 服务端的Messenegr
    var replyMessenger: Messenger? = null // 服务端给客户端发消息的Messenger
    var client: String? = null     // 客户端的包名
    private var surfaceViewRef: WeakReference<SurfaceView>? = null // 对UI层的surfaceview进行弱引用

    @RequiresApi(Build.VERSION_CODES.R)
    fun initSurfaceViewRef(sv: SurfaceView) {
        Log.d(TAG, "initSurfaceViewRef: 初始化——>HostManager.SurfacehView")
        surfaceViewRef = WeakReference(sv)
    }

    fun getSurfaceView(): SurfaceView? {
        return surfaceViewRef?.get()
    }

    @RequiresApi(Build.VERSION_CODES.R)
    fun sendSurfaceInfo2client(width: Int, height: Int) {
        val mSurface = getSurfaceView() ?: return
        val msg = Message.obtain()
        msg.what = MessengerUtil.MSG_SERVER_SURFACEINFO
        val bundle = Bundle()
        bundle.apply {
            putBinder(MessengerUtil.KEY_HOST_HOSTOKEN, mSurface.hostToken)
            putInt(MessengerUtil.KEY_HOST_WIDTH, width)
            putInt(MessengerUtil.KEY_HOST_HEIGHT, height)
            putInt(MessengerUtil.KEY_HOST_DISPLAYID, mSurface.display.displayId)
        }
        Log.d(TAG, "sendSurfaceInfo2client: $bundle")
        msg.data = bundle
        if (replyMessenger == null && !isSurfeced) {
            Log.d(TAG, "sendSurfaceInfo2client:replyMessenger是空着的！！ ")
        } else {
            replyMessenger?.send(msg)
        }
    }

    class MyHandler(looper: Looper) : Handler(looper) {
        //        val weakActivity = WeakReference(activity)
        //            val wActivity = weakActivity.get() ?: return
        @RequiresApi(Build.VERSION_CODES.R)
        override fun handleMessage(msg: Message) {
            when (msg.what) {
                MessengerUtil.MSG_CLIENT_PACKAGE -> {
                    client = msg.data.getString(MessengerUtil.KEY_CLIENT_PACKAGE)
                    Log.d(TAG, "handleMessage: 获得包名$client")
                    replyMessenger = msg.replyTo
                }
                // 获取surfacePackage
                MessengerUtil.MSG_CLIENT_SURFACEPKG -> {
                    val resBd = msg.data
                    val surPkg = resBd.getParcelable<SurfaceControlViewHost.SurfacePackage>(
                        KEY_CLIENT_SURFACEPKG
                    ) ?: return

                    val mSurface = getSurfaceView() ?: return
                    Log.d(TAG, "handleMessage:收到跨进程渲染的组建了吗 ")
                    mSurface.setChildSurfacePackage(surPkg)
                }
                // 客户端进程发送text改变请求
                MessengerUtil.MSG_CLIENT_TEXTCHANGE -> {
                    val uiHandler = MyHandler(Looper.getMainLooper())
                    uiHandler.post { invokeListener() }
                }

                else -> super.handleMessage(msg)
            }
        }
    }

    // 给MainActivity的回调接口
    interface textListener {
        fun changeText()
    }

    fun setTextListner(listener: textListener) {
        this.listener = listener
    }

    fun invokeListener() {
        listener.changeText()
    }
}
